<template>
  <div class="login">
    <el-row>
      <el-col :span="8" :offset="8">
        <el-form :model="user" status-icon :rules="rules" ref="userForm" label-width="100px" class="demo-ruleForm">

          <!-- 全局指令 -->
          <!-- <input type="text" v-focus> -->
          <input type="text" ref="myInput">

          <el-form-item label="账号" prop="name">
            <el-input type="text" v-model="user.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pass">
            <el-input type="password" v-model="user.pass" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitLogin" class="login-btn">登录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {mapActions} from 'vuex'

export default {
  name: 'LoginView',
  data() {
    const validatePass = (rule, value, callback) => { // 自定义密码验证
      const pat = /^\w+$/i;
      if(pat.test(value)) {
        callback();
      } else {
        callback(new Error('密码只能由字母、数字、下划线组成'));
      }
    };

    return {
      user: {
        name: '',
        pass: ''
      },
      rules: { // 表单验证规则
        name: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 10, message: '账号长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        pass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 16, message: '密码长度在 3 到 16 个字符', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // 这里必须选择 mounted 生命周期
    this.$refs.myInput.focus()
  },
  methods: {
    ...mapActions(['user/loginAction']),
    submitLogin() {
      // this.$refs.userForm 获取 el-form 组件，userForm 对应 el-form 组件上的 ref 属性值
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          // 应该在 actions 结束后，跳转路由，但是我不知道什么时候结束
          this['user/loginAction']({
            username: this.user.name,
            password: this.user.pass
          })
            .then(() => {
              this.$router.push('/')
            })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.el-button--primary.login-btn {
  width: 100%;
}
</style>